package cn.edu.hqu.cst.android.ljc.test3;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Button;

public class DisplayProgressBar extends AppCompatActivity {

    private int[] data = new int[100];
    int hasData = 0;

    final int PROGRESS_DIALOG = 0x112;
    //记录进度对话框的完成百分比
    int progressStatus = 0;
    ProgressDialog pd;

    //创建一个负责更新进度的Handler
    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            pd.setProgress(msg.arg1);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_progress_bar);

        Button display = findViewById(R.id.display);
        display.setOnClickListener(view -> showDialog(PROGRESS_DIALOG));
    }

    //创建进度条相关的信息
    @Override
    public Dialog onCreateDialog(int id, Bundle status) {
        switch (id) {
            case PROGRESS_DIALOG:
                pd = new ProgressDialog(this);
                pd.setMax(100);
                pd.setTitle("任务完成百分比");
                pd.setMessage("耗时任务的完成百分比");
                pd.setCancelable(false);
                pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                pd.setIndeterminate(false);
                break;
        }
        return pd;
    }

    //判断“加载”是否完成
    @Override
    public void onPrepareDialog(int id, Dialog dialog) {
        super.onPrepareDialog(id, dialog);
        switch (id) {
            case PROGRESS_DIALOG:
                pd.incrementProgressBy(-pd.getProgress());
                new Thread() {
                    public void run() {
                        while (progressStatus < 100) {
                            progressStatus = doWork();

                            Message msg = handler.obtainMessage();
                            msg.arg1 = progressStatus;
                            handler.sendMessage(msg);
                        }
                        if (progressStatus >= 100) {
                            pd.dismiss();
                        }
                    }
                }.start();
                break;
        }
    }

    //模拟一个耗时操作
    public int doWork() {
        data[hasData++] = (int) (Math.random() * 100);
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return hasData;
    }
}